window.onload = function () {
  fetchStudents();
  setupSearch();
};

let currentStudentId = null; // 当前操作的学员ID
let studentData = [];

// 获取学员数据并显示
function fetchStudents() {
  const tableBody = document.getElementById("student-table-body");
  tableBody.innerHTML = ""; // 清空表格内容

  fetch('http://localhost:8083/api/admin/student/list', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token') // 使用token进行身份验证
    },
    body: JSON.stringify({
      pageNum: 1, // 默认第一页
      pageSize: 10 // 默认每页显示10条
    })
  })
  .then(response => response.json())
  .then(data => {
    const studentList = data.data.records;
    studentList.forEach(student => {
      const row = document.createElement("tr");
      row.innerHTML = `
        <td>${student.id}</td>
        <td>${student.name}</td>
        <td>${student.realname}</td>
        <td>${student.gender}</td>
        <td>${student.contact}</td>
        <td>${student.email}</td>
        <td>${student.joinDate}</td>
        <td>${student.status}</td>
        <td>
          <button onclick="openModal('edit', ${student.id})">编辑</button>
          <button onclick="deleteStudent(${student.id})">删除</button>
          <button onclick="toggleStatus(${student.id})">审核</button>
        </td>
      `;
      tableBody.appendChild(row);
    });
  })
  .catch(error => {
    console.error("加载学员数据失败:", error);
  });
}

// 打开弹窗
function openModal(action, studentId = null) {
  const modal = document.getElementById("studentModal");
  const modalTitle = document.getElementById("modal-title");
  const saveBtn = document.getElementById("save-btn");

  if (action === 'create') {
    modalTitle.textContent = "新增学员";
    saveBtn.textContent = "保存";
    document.getElementById("student-name").value = ""; // 清空输入框
    document.getElementById("student-realname").value = "";
    document.getElementById("student-gender").value = "male";
    document.getElementById("student-contact").value = "";
    document.getElementById("student-email").value = "";
    document.getElementById("student-join-date").value = "";
    document.getElementById("student-status").value = "在读";
    currentStudentId = null;
  } else if (action === 'edit') {
    modalTitle.textContent = "编辑学员";
    saveBtn.textContent = "保存修改";
    currentStudentId = studentId;

    fetch(`http://localhost:8083/api/admin/student/${studentId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    .then(response => response.json())
    .then(data => {
      const student = data.data;
      document.getElementById("student-name").value = student.name;
      document.getElementById("student-realname").value = student.realname;
      document.getElementById("student-gender").value = student.gender;
      document.getElementById("student-contact").value = student.contact;
      document.getElementById("student-email").value = student.email;
      document.getElementById("student-join-date").value = student.joinDate;
      document.getElementById("student-status").value = student.status;
    })
    .catch(error => {
      console.error("获取学员数据失败:", error);
    });
  }

  modal.style.display = "block"; // 打开弹窗
}

// 关闭弹窗
document.getElementById("cancel-btn").addEventListener("click", function() {
  const modal = document.getElementById("studentModal");
  modal.style.display = "none"; // 关闭弹窗
});

// 保存或编辑学员
document.getElementById("student-form").addEventListener("submit", function (event) {
  event.preventDefault(); // 阻止表单默认提交行为

  const name = document.getElementById("student-name").value.trim();
  const realname = document.getElementById("student-realname").value.trim();
  const gender = document.getElementById("student-gender").value.trim();
  const contact = document.getElementById("student-contact").value.trim();
  const email = document.getElementById("student-email").value.trim();
  const joinDate = document.getElementById("student-join-date").value.trim();
  const status = document.getElementById("student-status").value.trim();

  if (name === "" || realname === "" || gender === "" || contact === "" || email === "" || joinDate === "" || status === "") {
    alert("所有字段都是必填项");
    return;
  }

  const studentDTO = {
    name,
    realname,
    gender,
    contact,
    email,
    joinDate,
    status
  };

  if (currentStudentId === null) {
    // 新增学员
    fetch('http://localhost:8083/api/admin/student/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify(studentDTO)
    })
    .then(response => response.json())
    .then(() => {
      fetchStudents(); // 重新加载学员数据到表格
      const modal = document.getElementById("studentModal");
      modal.style.display = "none"; // 关闭弹窗
    })
    .catch(error => {
      console.error("新增学员失败:", error);
    });
  } else {
    // 编辑学员
    studentDTO.id = currentStudentId;
    fetch('http://localhost:8083/api/admin/student/update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: JSON.stringify(studentDTO)
    })
    .then(response => response.json())
    .then(() => {
      fetchStudents(); // 重新加载学员数据到表格
      const modal = document.getElementById("studentModal");
      modal.style.display = "none"; // 关闭弹窗
    })
    .catch(error => {
      console.error("编辑学员失败:", error);
    });
  }
});

// 删除学员
function deleteStudent(studentId) {
  fetch(`http://localhost:8083/api/admin/student/delete/${studentId}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    }
  })
  .then(response => response.json())
  .then(() => {
    fetchStudents(); // 重新加载学员数据
  })
  .catch(error => {
    console.error("删除学员失败:", error);
  });
}

// 审核学员状态（在读 <-> 离校）
function toggleStatus(studentId) {
  fetch(`http://localhost:8083/api/admin/student/status/${studentId}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + localStorage.getItem('token')
    },
    body: JSON.stringify({ status: 1 }) // 假设1是“在读”状态，0是“离校”状态
  })
  .then(response => response.json())
  .then(() => {
    fetchStudents(); // 重新加载学员数据
  })
  .catch(error => {
    console.error("更新学员状态失败:", error);
  });
}

// 搜索学员
document.getElementById("search-btn").addEventListener("click", function() {
  const searchTerm = document.getElementById("search-student-name").value.toLowerCase();
  const statusFilter = document.getElementById("search-status").value;

  // 过滤数据
  const filteredData = studentData.filter(student =>
    student.name.toLowerCase().includes(searchTerm) &&
    (statusFilter === "" || student.status === statusFilter)
  );

  // 渲染过滤后的数据
  renderStudentData(filteredData);
});

// 渲染学员数据
function renderStudentData(data) {
  const tableBody = document.getElementById("student-table-body");
  tableBody.innerHTML = ""; // 清空表格内容
  data.forEach(student => {
    const row = document.createElement("tr");
    row.innerHTML = `
      <td>${student.id}</td>
      <td>${student.name}</td>
      <td>${student.realname}</td>
      <td>${student.gender}</td>
      <td>${student.contact}</td>
      <td>${student.email}</td>
      <td>${student.joinDate}</td>
      <td>${student.status}</td>
      <td>
        <button onclick="openModal('edit', ${student.id})">编辑</button>
        <button onclick="deleteStudent(${student.id})">删除</button>
        <button onclick="toggleStatus(${student.id})">审核</button>
      </td>
    `;
    tableBody.appendChild(row);
  });
}

// 批量导入学员功能
function importStudents() {
  const fileInput = document.getElementById("import-file");
  const file = fileInput.files[0];

  if (!file) {
    alert("请选择一个文件进行导入");
    return;
  }

  const fileExtension = file.name.split('.').pop().toLowerCase();

  // 判断文件类型：CSV 或 Excel
  if (fileExtension === "csv") {
    // 处理 CSV 文件
    parseCSV(file);
  } else if (fileExtension === "xlsx") {
    // 处理 Excel 文件
    parseExcel(file);
  } else {
    alert("只支持 CSV 或 Excel 文件格式！");
  }
}

// 解析 CSV 文件
function parseCSV(file) {
  Papa.parse(file, {
    complete: function(results) {
      console.log("CSV 数据解析结果:", results.data);
      importStudentData(results.data);
    },
    header: true, // 处理 CSV 的表头
    skipEmptyLines: true, // 跳过空行
  });
}

// 解析 Excel 文件
function parseExcel(file) {
  const reader = new FileReader();

  reader.onload = function(e) {
    const data = e.target.result;
    const workbook = XLSX.read(data, { type: 'binary' });

    // 假设第一个 sheet 包含学员数据
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });

    console.log("Excel 数据解析结果:", rows);
    importStudentData(rows);
  };

  reader.readAsBinaryString(file);
}

// 将解析的数据导入到学员数据数组
function importStudentData(data) {
  // 假设数据是按顺序：姓名, 年级, 性别, 联系方式, 加入日期, 状态
  data.forEach(row => {
    const [name, realname, gender, contact, email, joinDate, status] = row;

    if (name && realname && gender && contact && email && joinDate && status) {
      const studentDTO = {
        name,
        realname,
        gender,
        contact,
        email,
        joinDate,
        status
      };

      fetch('http://localhost:8083/api/admin/student/add', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        body: JSON.stringify(studentDTO)
      })
      .then(response => response.json())
      .then(() => {
        fetchStudents(); // 重新加载学员数据到表格
        alert("学员数据导入成功！");
      })
      .catch(error => {
        console.error("导入学员数据失败:", error);
      });
    }
  });
}

// 点击退出按钮时的跳转操作
document.querySelector(".logout-btn").addEventListener("click", function() {
  window.location.href = "../login.html"; // 跳转到登录页面
});
